﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;

public class FileCheckStep : AssetsAction
{
    public int maxCount;
    public int maxLength;
    public override string Tips
    { 
        get 
        {
            return "检测资源完整性";
        }
    }
    public override float Progress
    {
        get
        {
            if (_len == 0)
                return 0;
            double a = _len;
            double p = _pos;
            return (float)(p / a);
        }
    }
    public override void Reset()
    {
        _done = true;
        checking = false;
        NeedAgree = false;
    }
    
    bool checking;
    public bool NeedAgree;
    List<AssetsChecker.AssetsSection> tmpList;
    public void FileCheckTask()
    {
        if (checking)
            return;
#if DEBUG
        if(AssetsVersionControl.NetVersion==null)
        {
            _done = true;
            return;
        }
#endif
        _done = false;
        checking = true;
        AssetsChecker checker = new AssetsChecker();
        checker.IgnoreSection = AssetsVersionControl.sec_Public;
        checker.RootSection = AssetsVersionControl.sec_Assets;
        checker.CheckAsync(AssetsVersionControl.NetVersion.ini, AssetsVersionControl.BuildInVersion.ini,
            LocalSetting.AssetsPath + "/",(o)=> {
                AssetsManager.Parts = o.Parts;
                tmpList = o.Parts[0].Result;
                maxLength = o.Parts[0].Length;
                if (maxLength > 0)
                {
                    NeedAgree = true;
                }
                else
                {
                    _done = true;
                    checking = false;
                }
            });
    }
    public override void Update()
    {
        if(GetCurrentStep()==this)
        {
            if (!checking)
                FileCheckTask();
        }
    }
    public void Download()
    {
        Reset();
        var download = GetStep<DownloadStep>();
        if (download == null)
            return;
        string url = LocalSetting.bundleUrl + AssetsType + "/";
        for (int i = 0; i < tmpList.Count; i++)
        {
            var sec = tmpList[i];
            if(sec.Name==AssetsVersionControl.sec_Assets)
            {
                download.DownLoadAssets(sec.assets, sec.Name, url, false);
            }
            else
            {
                download.DownLoadAssets(sec.assets, sec.Name, url, true);
            }
        }
        tmpList.Clear();
    }
}